package com.grt192.controller.breakaway.teleop;

import com.grt192.core.EventController;
import com.grt192.core.Sensor;
import com.grt192.event.SensorChangeListener;
import com.grt192.event.SensorEvent;
import com.grt192.event.component.ButtonListener;
import com.grt192.mechanism.GRTDriverStation;
import com.grt192.mechanism.breakaway.Kicker;
import com.grt192.sensor.GRTJoystick;
import com.grt192.sensor.GRTSwitch;

/**
 *
 * @author alvin and nikhil
 */
public class KickerController extends EventController
        implements ButtonListener, SensorChangeListener {

    public static final int COOLDOWN_TIME = 2000; //ms
    private double lastFired;

    public KickerController(GRTDriverStation ds, Kicker k) {
        addMechanism("Kicker", k);
        addMechanism("DriverStation", ds);
        ((GRTJoystick) (ds.getSensor("secondaryJoystick"))).addButtonListener(this);
        ((GRTSwitch) k.getSensor("LimitSwitch")).addSensorChangeListener(this);
        lastFired = 0;
    }

    public void buttonUp(SensorEvent e, String key) {
        if (key.equals("Button1") 
                && System.currentTimeMillis() - lastFired > COOLDOWN_TIME
                && !((Kicker) getMechanism("Kicker")).isKicking()) {
            lastFired = System.currentTimeMillis();
            ((Kicker) getMechanism("Kicker")).kick();

        } else if (key.equals("Button2") || key.equals("Button3")) {
            ((Kicker) getMechanism("Kicker")).stopKick();
        }
    }

    public void buttonDown(SensorEvent e, String key) {
        //Manual overrides for directional control over the motor.
        if (key.equals("Button2")) {
            ((Kicker) getMechanism("Kicker")).reverse();
        }
        if (key.equals("Button3")) {
            ((Kicker) getMechanism("Kicker")).kick();
        }
    }

    public void sensorStateChanged(SensorEvent e, String key) {
        if (e.getData(key) == Sensor.FALSE
                && ((Kicker) getMechanism("Kicker")).isKicking()) {
            ((Kicker) getMechanism("Kicker")).stopKick();
        }
    }
}
